//
//  HomeRefreshControl.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/6/2.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit

class HomeRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        
        setupUI()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        // 停止转圈loading动画
        refreshView.stopLoadingViewAnimation()
        
        // 复位转圈动画的标记
        loadingViewAnimationFalg = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
        //1.添加子控件
        addSubview(refreshView)
        
        //2.布局子控件
        refreshView.xmg_AlignInner(type: .Center, referView: self, size: CGSize(width: 170, height: 60))
        
        /*
         1.当用户下拉到一定程度的时候需要旋转箭头
         2.当用户上推到一定程度的时候需要旋转箭头
         3.当下拉刷新控件触发刷新方法的时候, 需要显示刷新界面(转轮)
         
         通过观察:
         越往下拉: Y值就越小
         越往上推: Y值就越大
         */
        addObserver(self, forKeyPath: "frame", options: .New, context: nil)
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    private var rotateTipViewFlag : Bool = false
    private var loadingViewAnimationFalg : Bool = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        
        // 过滤不需要的数据
        if frame.origin.y == 0 {
            return
        }
        
        // 如果正在刷新, 那么就显示圆圈转动 , 不需要下面的翻箭头了
        if refreshing && !loadingViewAnimationFalg{
            
            loadingViewAnimationFalg = true
            refreshView.startLoadingViewAnimation()
            return
        }
        
        if frame.origin.y >= -50 && !rotateTipViewFlag{
            
            refreshView.rotateArrowImage(rotateTipViewFlag)
            
            rotateTipViewFlag = true
        }else if frame.origin.y < -50 && rotateTipViewFlag{
            
            refreshView.rotateArrowImage(rotateTipViewFlag)
            rotateTipViewFlag = false
        }
    }
    
    //MARK:- 懒加载
    private lazy var refreshView: HomeRefreshView = HomeRefreshView(frame: CGRect(x: 0, y: 0, width: 170, height: 60))
}

private class HomeRefreshView : UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initSubviews()
    }
    
    /**
     开启转圈loading动画
     */
    func startLoadingViewAnimation()
    {
        tipView.hidden = false
        tipView.loadingView.layer.removeAllAnimations()
        
        // 1,创建动画
        let animation = CABasicAnimation()
        // 2,设置动画属性
        animation.keyPath = "transform.rotation"
        animation.repeatCount = MAXFLOAT
        animation.toValue = M_PI * 2
        animation.duration = 1.0
        animation.removedOnCompletion = false
        // 3,将动画添加到图层上
        tipView.loadingView.layer.addAnimation(animation, forKey: "animation")
    }
    
    /**
     关闭转圈loading动画
     */
    func stopLoadingViewAnimation()
    {
        tipView.hidden = true
        tipView.loadingView.layer.removeAllAnimations()
    }
    
    /**
     旋转箭头
     */
    func rotateArrowImage(flag: Bool) {
    
        var angle = M_PI
        angle += flag ? -0.01 : 0.01
        
        textLabel.text = flag ? "释放刷新" : "下拉刷新"
        
        UIView.animateWithDuration(0.2, animations: {
            self.arrowView.transform = CGAffineTransformRotate(self.arrowView.transform, CGFloat(angle))
        })
    }
    
    private func initSubviews()
    {
        backgroundColor = UIColor.whiteColor()
        
        addSubview(arrowView)
        addSubview(textLabel)
        addSubview(tipView)
        
        arrowView.xmg_AlignInner(type: .TopLeft, referView: self, size: CGSize(width: 32, height: 32), offset: CGPoint(x: 14, y: 14))
        
        textLabel.xmg_AlignHorizontal(type: .TopRight, referView: arrowView, size: CGSize(width: 100, height: 32), offset: CGPoint(x: 10, y: 0))
        
        tipView.xmg_Fill(self)
        tipView.hidden = true
    }
    
    // MARK: - 懒加载
    private lazy var arrowView : UIImageView = {
    
        let iv = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        
        return iv
    }()
    
    private lazy var textLabel : UILabel = {
    
        let lb = UILabel()
        lb.text = "下拉刷新"
        lb.textColor = UIColor.orangeColor()
        return lb
    }()
    
    private lazy var tipView : HomeTipView = HomeTipView(frame: CGRect(x: 0, y: 0, width: 170, height: 60))
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private class HomeTipView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initSubviews()
    }
    
    private func initSubviews()
    {
        backgroundColor = UIColor.whiteColor()
        
        addSubview(loadingView)
        addSubview(textLabel)
        
        loadingView.xmg_AlignInner(type: .TopLeft, referView: self, size: CGSize(width: 32, height: 32), offset: CGPoint(x: 14, y: 14))
        
        textLabel.xmg_AlignHorizontal(type: .TopRight, referView: loadingView, size: CGSize(width: 100, height: 32), offset: CGPoint(x: 10, y: 0))
    }
    
    // MARK: - 懒加载
    private lazy var loadingView : UIImageView = {
        
        let iv = UIImageView(image: UIImage(named: "tableview_loading"))
        
        return iv
    }()
    
    private lazy var textLabel : UILabel = {
        
        let lb = UILabel()
        lb.text = "正在刷新"
        lb.textColor = UIColor.orangeColor()
        return lb
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
